package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.pojo.DtsStorage;
import com.qf.service.StorageService;
import com.qf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Wy
 * @version V1.0
 * @Project MavenDemo
 * @Package com.qf.controller
 * @Description:
 * @Date 2022/6/20 17:25
 */
@RestController
@CrossOrigin("*")
@RequestMapping("/storage")
public class StorageController {

    @Autowired
    private StorageService service;

   @RequestMapping("/list")
    public Object list(String key, String name,
                       @RequestParam(defaultValue = "1")Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @RequestParam(defaultValue = "add_time") String sort,
                       @RequestParam(defaultValue = "desc") String order){
       //1. 查询并返回分页对象
       IPage<DtsStorage> dtsStorageIPage = service.queryStoragePage(key, name, page, limit, sort, order);
       //获取结果集
       List<DtsStorage> records = dtsStorageIPage.getRecords();
       //获取查询总条数
       long total = dtsStorageIPage.getTotal();
       Map<String,Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items",records);


       return ResponseUtil.ok(data);
   }

   @RequestMapping("/create")
   public Object create(@RequestParam("file") MultipartFile file) throws Exception {
       //1. 获取文件名
       String filename = file.getOriginalFilename();
       if(StringUtils.isEmpty(filename)){
           throw  new RuntimeException("传入的文件为空");
       }
       //2. 获取文件扩展名
       String ext = filename.substring(filename.lastIndexOf("."));
       //3. 获取文件大小
       long size = file.getSize();
       //4. 获取文件内容
       byte[] bytes = file.getBytes();
       //5. 上传并返回上传保存后的文件对象
       DtsStorage add = service.add(filename, (int) size, ext, bytes);



       return  ResponseUtil.ok(add);
   }
    @RequestMapping("/update")
    public Object update(@RequestBody DtsStorage dtsStorage){
        int update = service.update(dtsStorage);
   if(update==0){
       return  ResponseUtil.fail();
   }
   return  ResponseUtil.ok();


    }

    @PostMapping("/delete")
    public Object delect(@RequestBody DtsStorage dtsStorage){
        //1. 提取文件对象中的key, 也就是阿里云中保存的文件名
        String key = dtsStorage.getKey();
        //2. 如果key为空, 那么不允许删除
        if(StringUtils.isEmpty(key)){
            return  ResponseUtil.badArgument();
        }
        int delect = service.delect(key);

        return  ResponseUtil.ok();
    }
}
